package com.xvdong.audioplayer.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

import com.xvdong.audioplayer.MusicPlayer;
import com.xvdong.audioplayer.R;
import com.xvdong.audioplayer.ui.MainActivity;

/**
 * Created by xvDong on 2023/10/20.
 */

public class ForegroundService extends Service {

    private final String CHANNEL_ID = "lxdVideoPlayChannel";
    private static final int NOTIFICATION_ID = 1;

    // 播放状态
    public static final int STATE_IDLE = 0;
    public static final int STATE_PLAYING = 1;
    public static final int STATE_PAUSED = 2;

    private int currentState = STATE_IDLE;
    private String currentSong = "未知歌曲";
    private MusicPlayer mMediaPlayer;

    // 绑定服务相关
    private final IBinder binder = new MusicBinder();

    public void setMediaPlay(MusicPlayer mediaPlay) {
        mMediaPlayer = mediaPlay;
    }

    public class MusicBinder extends Binder {
        public ForegroundService getService() {
            return ForegroundService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getAction() != null) {
            handleAction(intent.getAction());
        } else {
            // 正常启动服务
            startForegroundService();
        }
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private void handleAction(String action) {
        switch (action) {
            case "PLAY":
                playMusic();
                break;
            case "PAUSE":
                pauseMusic();
                break;
            case "STOP":
                stopMusic();
                break;
            case "NEXT":
                nextSong();
                break;
            case "PREVIOUS":
                previousSong();
                break;
        }
        updateNotification();
    }

    private void startForegroundService() {
        Notification notification = createNotification();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
        } else {
            startForeground(NOTIFICATION_ID, notification);
        }
    }

    private Notification createNotification() {
        // 创建通知内容
        String contentText;
        int playPauseIcon;

        switch (currentState) {
            case STATE_PLAYING:
                contentText = "正在播放: " + mMediaPlayer.getCurrentSongName();
                playPauseIcon = R.mipmap.pause;
                break;
            case STATE_PAUSED:
                contentText = "已暂停: " + mMediaPlayer.getCurrentSongName();
                playPauseIcon = R.mipmap.play;
                break;
            default:
                contentText = "音乐播放器";
                playPauseIcon = R.mipmap.pause;
        }

        // 创建各种PendingIntent
        Intent mainIntent = new Intent(this, MainActivity.class);
        mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent mainPendingIntent = createPendingIntent(mainIntent, 0);

        // 播放/暂停动作
        Intent playPauseIntent = new Intent(this, ForegroundService.class);
        playPauseIntent.setAction(currentState == STATE_PLAYING ? "PAUSE" : "PLAY");
        PendingIntent playPausePendingIntent = createPendingIntent(playPauseIntent, 1);

        // 下一首动作
        Intent nextIntent = new Intent(this, ForegroundService.class);
        nextIntent.setAction("NEXT");
        PendingIntent nextPendingIntent = createPendingIntent(nextIntent, 2);

        // 上一首动作
        Intent previousIntent = new Intent(this, ForegroundService.class);
        previousIntent.setAction("PREVIOUS");
        PendingIntent previousPendingIntent = createPendingIntent(previousIntent, 3);

        // 停止动作
        Intent stopIntent = new Intent(this, ForegroundService.class);
        stopIntent.setAction("STOP");
        PendingIntent stopPendingIntent = createPendingIntent(stopIntent, 4);

        // 构建通知
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("音乐播放器")
                .setContentText(contentText)
                .setSmallIcon(R.mipmap.logo)
                .setContentIntent(mainPendingIntent) // 点击通知打开应用
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setOngoing(currentState == STATE_PLAYING)

                // 添加控制动作
                .addAction(R.mipmap.play_previous, "上一首", previousPendingIntent)
                .addAction(playPauseIcon, currentState == STATE_PLAYING ? "暂停" : "播放", playPausePendingIntent)
                .addAction(R.mipmap.play_next, "下一首", nextPendingIntent)
                .addAction(R.mipmap.stop, "停止", stopPendingIntent)

                // 媒体样式（Android 5.0+）
                .setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
                        .setShowActionsInCompactView(1, 2, 3) // 在折叠状态下显示的动作索引
                        .setShowCancelButton(true)
                        .setCancelButtonIntent(stopPendingIntent))

                .build();
    }

    private PendingIntent createPendingIntent(Intent intent, int requestCode) {
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            flags |= PendingIntent.FLAG_IMMUTABLE;
        }

        if (intent.getComponent() != null &&
                intent.getComponent().getClassName().equals(ForegroundService.class.getName())) {
            return PendingIntent.getService(this, requestCode, intent, flags);
        } else {
            return PendingIntent.getActivity(this, requestCode, intent, flags);
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "音乐播放",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("音乐播放通知");
            channel.setShowBadge(false);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    // 音乐控制方法
    public void playMusic() {
        currentState = STATE_PLAYING;
        // 这里添加实际的播放逻辑
        if (mMediaPlayer != null){
            mMediaPlayer.resume();
        }
    }

    public void pauseMusic() {
        currentState = STATE_PAUSED;
        // 这里添加实际的暂停逻辑
        if (mMediaPlayer != null){
            mMediaPlayer.pause();
        }
    }

    public void stopMusic() {
        currentState = STATE_IDLE;
        // 这里添加实际的停止逻辑
        if (mMediaPlayer != null){
            mMediaPlayer.releaseMediaPlayer();
        }
        stopForeground(true);
        stopSelf();
    }

    public void nextSong() {
        // 切换到下一首
        currentSong = "下一首歌曲";
        currentState = STATE_PLAYING;
        if (mMediaPlayer != null){
            mMediaPlayer.next();
        }
    }

    public void previousSong() {
        // 切换到上一首
        currentSong = "上一首歌曲";
        currentState = STATE_PLAYING;
        if (mMediaPlayer != null){
            mMediaPlayer.previous();
        }
    }

    public void setCurrentSong(String songName) {
        this.currentSong = songName;
        updateNotification();
    }

    public int getCurrentState() {
        return currentState;
    }

    public String getCurrentSong() {
        return currentSong;
    }

    private void updateNotification() {
        Notification notification = createNotification();
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 清理资源
        // if (mediaPlayer != null) {
        //     mediaPlayer.release();
        // }
    }
}
